package db

import (
	"boy-go/pkg/request"
	"fmt"
	"gorm.io/gorm"
	"regexp"
	"strings"
)

func BuildPageAndOrder(db *gorm.DB, pageReq *request.PageRequest, defaultOrder string) *gorm.DB {
	db = BuildPage(db, pageReq)
	db = BuildOrder(db, pageReq, defaultOrder)
	return db
}
func BuildPageAndOrderSQL(sql *string, pageReq *request.PageRequest, defaultOrder string) {
	if defaultOrder != "" {
		*sql = *sql + " ORDER BY " + defaultOrder
	}
	offSet := 0
	limit := 10
	if pageReq.PageNum > 0 {
		offSet = (pageReq.PageNum - 1) * limit
	}
	if pageReq.PageSize > 0 {
		limit = pageReq.PageSize
	}
	*sql = *sql + fmt.Sprintf(" LIMIT %d,%d ", offSet, limit)
}
func BuildPage(db *gorm.DB, pageReq *request.PageRequest) *gorm.DB {
	if pageReq.PageNum > 0 {
		db = db.Offset((pageReq.PageNum - 1) * pageReq.PageSize)
	}
	if pageReq.PageSize > 0 {
		db = db.Limit(pageReq.PageSize)
	}
	return db
}
func BuildOrder(db *gorm.DB, pageReq *request.PageRequest, defaultOrder string) *gorm.DB {
	if pageReq.OrderByColumn != nil && pageReq.IsAsc != nil {
		isAsc := *pageReq.IsAsc
		if *pageReq.IsAsc == "descending" {
			isAsc = "desc"
		}
		if *pageReq.IsAsc == "ascending" {
			isAsc = "asc"
		}
		db = db.Order(camelToSnake(*pageReq.OrderByColumn) + " " + isAsc)
	} else {
		if defaultOrder != "" {
			db = db.Order(defaultOrder)
		}
	}
	return db
}

// 驼峰转下划线
func camelToSnake(s string) string {
	// 匹配大写字母的位置，在其前面加上下划线，并转为小写
	re := regexp.MustCompile("([a-z0-9])([A-Z])")
	snake := re.ReplaceAllStringFunc(s, func(str string) string {
		return str[:1] + "_" + str[1:]
	})
	return strings.ToLower(snake)
}
